﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using GameServer.Managers;
using GameServer.Virtual_Objects.User;
using GameServer.Virtual_Objects.Room;
using GameServer.Networking.Packets;

namespace GameServer.Networking.Handlers
{
    class HANDLE_QUICK_JOIN : PacketHandler
    {
        public override void Handle(virtualUser User)
        {
            try
            {
                ArrayList Rooms = RoomManager.getRoomsInChannel(User.Channel, new Random().Next(0, 5));
                foreach (virtualRoom Room in Rooms)
                {
                    if (User.Room != null) return;
                    if (Room.Players.Count >= Room.MaxPlayers || Room.Channel != 4)
                        return;
                    if (Room.EnablePassword == 1)
                        return;
                    if (Room.UserLimit == true)
                        return;

                    if (Room.joinUser(User) == true)
                    {
                        User.isReady = false;
                        User.send(new PACKET_ROOM_UDP(User, Room.Players));
                        foreach (Virtual_Objects.User.virtualUser tempSpectator in Room.Spectators)
                            User.send(new PACKET_ROOM_UDP_SPECTATE(tempSpectator));
                        User.send(new PACKET_JOIN_ROOM(User, Room));
                        ArrayList tempPlayers = new ArrayList();

                        tempPlayers.Add(User);
                        foreach (Virtual_Objects.User.virtualUser RoomUser in Room.Players)
                            RoomUser.send(new PACKET_ROOM_UDP(RoomUser, tempPlayers));
                        foreach (Virtual_Objects.User.virtualUser SpectatorUser in Room.Spectators)
                            SpectatorUser.send(new PACKET_ROOM_UDP(SpectatorUser, tempPlayers));


                        /* Send out changed Room Data */

                        UserManager.refreshRoom(Room);
                        return;
                    }
                }
            }
            catch(Exception ex)
            {
                Log.WriteError("Error at QuickJoin: " + ex.Message);
            }
        }
    }
}
